home *** CD-ROM | disk | FTP | other *** search
/ IRIX Base Documentation 2002 November / SGI IRIX Base Documentation 2002 November.iso / usr / share / catman / u_man / cat1 / perlfaq8.z / perlfaq8
Encoding:
Text File  |  2002-10-03  |  61.3 KB  |  1,453 lines

  1.  
  2.  
  3.  
  4. PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))
  5.  
  6.  
  7.  
  8. NNNNAAAAMMMMEEEE
  9.      perlfaq8 - System Interaction ($Revision: 1.1 $, $Date: 2002/05/07
  10.      00:07:32 $)
  11.  
  12. DDDDEEEESSSSCCCCRRRRIIIIPPPPTTTTIIIIOOOONNNN
  13.      This section of the Perl FAQ covers questions involving operating system
  14.      interaction.  This involves interprocess communication (IPC), control
  15.      over the user-interface (keyboard, screen and pointing devices), and most
  16.      anything else not related to data manipulation.
  17.  
  18.      Read the FAQs and documentation specific to the port of perl to your
  19.      operating system (eg, the _p_e_r_l_v_m_s manpage, the _p_e_r_l_p_l_a_n_9 manpage, ...).
  20.      These should contain more detailed information on the vagaries of your
  21.      perl.
  22.  
  23.      HHHHoooowwww ddddoooo IIII ffffiiiinnnndddd oooouuuutttt wwwwhhhhiiiicccchhhh ooooppppeeeerrrraaaattttiiiinnnngggg ssssyyyysssstttteeeemmmm IIII''''mmmm rrrruuuunnnnnnnniiiinnnngggg uuuunnnnddddeeeerrrr????
  24.  
  25.      The $^O variable ($OSNAME if you use English) contains the operating
  26.      system that your perl binary was built for.
  27.  
  28.      HHHHoooowwww ccccoooommmmeeee _e_x_e_c() doesn't return?
  29.  
  30.      Because that's what it does: it replaces your currently running program
  31.      with a different one.  If you want to keep going (as is probably the case
  32.      if you're asking this question) use _s_y_s_t_e_m() instead.
  33.  
  34.      HHHHoooowwww ddddoooo IIII ddddoooo ffffaaaannnnccccyyyy ssssttttuuuuffffffff wwwwiiiitttthhhh tttthhhheeee kkkkeeeeyyyybbbbooooaaaarrrrdddd////ssssccccrrrreeeeeeeennnn////mmmmoooouuuusssseeee????
  35.  
  36.      How you access/control keyboards, screens, and pointing devices ("mice")
  37.      is system-dependent.  Try the following modules:
  38.  
  39.      Keyboard
  40.  
  41.              Term::Cap                   Standard perl distribution
  42.              Term::ReadKey               CPAN
  43.              Term::ReadLine::Gnu         CPAN
  44.              Term::ReadLine::Perl        CPAN
  45.              Term::Screen                CPAN
  46.  
  47.  
  48.      Screen
  49.  
  50.              Term::Cap                   Standard perl distribution
  51.              Curses                      CPAN
  52.              Term::ANSIColor             CPAN
  53.  
  54.  
  55.      Mouse
  56.  
  57.              Tk                          CPAN
  58.  
  59.  
  60.  
  61.  
  62.  
  63.                                                                         PPPPaaaaggggeeee 1111
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70. PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))
  71.  
  72.  
  73.  
  74.      Some of these specific cases are shown below.
  75.  
  76.      HHHHoooowwww ddddoooo IIII pppprrrriiiinnnntttt ssssoooommmmeeeetttthhhhiiiinnnngggg oooouuuutttt iiiinnnn ccccoooolllloooorrrr????
  77.  
  78.      In general, you don't, because you don't know whether the recipient has a
  79.      color-aware display device.  If you know that they have an ANSI terminal
  80.      that understands color, you can use the Term::ANSIColor module from CPAN:
  81.  
  82.          use Term::ANSIColor;
  83.          print color("red"), "Stop!\n", color("reset");
  84.          print color("green"), "Go!\n", color("reset");
  85.  
  86.      Or like this:
  87.  
  88.          use Term::ANSIColor qw(:constants);
  89.          print RED, "Stop!\n", RESET;
  90.          print GREEN, "Go!\n", RESET;
  91.  
  92.  
  93.      HHHHoooowwww ddddoooo IIII rrrreeeeaaaadddd jjjjuuuusssstttt oooonnnneeee kkkkeeeeyyyy wwwwiiiitttthhhhoooouuuutttt wwwwaaaaiiiittttiiiinnnngggg ffffoooorrrr aaaa rrrreeeettttuuuurrrrnnnn kkkkeeeeyyyy????
  94.  
  95.      Controlling input buffering is a remarkably system-dependent matter.  If
  96.      most systems, you can just use the ssssttttttttyyyy command as shown in the getc
  97.      entry in the _p_e_r_l_f_u_n_c manpage, but as you see, that's already getting you
  98.      into portability snags.
  99.  
  100.          open(TTY, "+</dev/tty") or die "no tty: $!";
  101.          system "stty  cbreak </dev/tty >/dev/tty 2>&1";
  102.          $key = getc(TTY);           # perhaps this works
  103.          # OR ELSE
  104.          sysread(TTY, $key, 1);      # probably this does
  105.          system "stty -cbreak </dev/tty >/dev/tty 2>&1";
  106.  
  107.      The Term::ReadKey module from CPAN offers an easy-to-use interface that
  108.      should be more efficient than shelling out to ssssttttttttyyyy for each key.  It even
  109.      includes limited support for Windows.
  110.  
  111.          use Term::ReadKey;
  112.          ReadMode('cbreak');
  113.          $key = ReadKey(0);
  114.          ReadMode('normal');
  115.  
  116.      However, that requires that you have a working C compiler and can use it
  117.      to build and install a CPAN module.  Here's a solution using the standard
  118.      POSIX module, which is already on your systems (assuming your system
  119.      supports POSIX).
  120.  
  121.          use HotKey;
  122.          $key = readkey();
  123.  
  124.      And here's the HotKey module, which hides the somewhat mystifying calls
  125.      to manipulate the POSIX termios structures.
  126.  
  127.  
  128.  
  129.                                                                         PPPPaaaaggggeeee 2222
  130.  
  131.  
  132.  
  133.  
  134.  
  135.  
  136. PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))
  137.  
  138.  
  139.  
  140.          # HotKey.pm
  141.          package HotKey;
  142.  
  143.          @ISA = qw(Exporter);
  144.          @EXPORT = qw(cbreak cooked readkey);
  145.  
  146.          use strict;
  147.          use POSIX qw(:termios_h);
  148.          my ($term, $oterm, $echo, $noecho, $fd_stdin);
  149.  
  150.          $fd_stdin = fileno(STDIN);
  151.          $term     = POSIX::Termios->new();
  152.          $term->getattr($fd_stdin);
  153.          $oterm     = $term->getlflag();
  154.  
  155.          $echo     = ECHO | ECHOK | ICANON;
  156.          $noecho   = $oterm & ~$echo;
  157.  
  158.          sub cbreak {
  159.              $term->setlflag($noecho);  # ok, so i don't want echo either
  160.              $term->setcc(VTIME, 1);
  161.              $term->setattr($fd_stdin, TCSANOW);
  162.          }
  163.  
  164.          sub cooked {
  165.              $term->setlflag($oterm);
  166.              $term->setcc(VTIME, 0);
  167.              $term->setattr($fd_stdin, TCSANOW);
  168.          }
  169.  
  170.          sub readkey {
  171.              my $key = '';
  172.              cbreak();
  173.              sysread(STDIN, $key, 1);
  174.              cooked();
  175.              return $key;
  176.          }
  177.  
  178.          END { cooked() }
  179.  
  180.          1;
  181.  
  182.  
  183.      HHHHoooowwww ddddoooo IIII cccchhhheeeecccckkkk wwwwhhhheeeetttthhhheeeerrrr iiiinnnnppppuuuutttt iiiissss rrrreeeeaaaaddddyyyy oooonnnn tttthhhheeee kkkkeeeeyyyybbbbooooaaaarrrrdddd????
  184.  
  185.      The easiest way to do this is to read a key in nonblocking mode with the
  186.      Term::ReadKey module from CPAN, passing it an argument of -1 to indicate
  187.      not to block:
  188.  
  189.          use Term::ReadKey;
  190.  
  191.          ReadMode('cbreak');
  192.  
  193.  
  194.  
  195.                                                                         PPPPaaaaggggeeee 3333
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202. PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))
  203.  
  204.  
  205.  
  206.          if (defined ($char = ReadKey(-1)) ) {
  207.              # input was waiting and it was $char
  208.          } else {
  209.              # no input was waiting
  210.          }
  211.  
  212.          ReadMode('normal');                  # restore normal tty settings
  213.  
  214.  
  215.      HHHHoooowwww ddddoooo IIII cccclllleeeeaaaarrrr tttthhhheeee ssssccccrrrreeeeeeeennnn????
  216.  
  217.      If you only have to so infrequently, use system:
  218.  
  219.          system("clear");
  220.  
  221.      If you have to do this a lot, save the clear string so you can print it
  222.      100 times without calling a program 100 times:
  223.  
  224.          $clear_string = `clear`;
  225.          print $clear_string;
  226.  
  227.      If you're planning on doing other screen manipulations, like cursor
  228.      positions, etc, you might wish to use Term::Cap module:
  229.  
  230.          use Term::Cap;
  231.          $terminal = Term::Cap->Tgetent( {OSPEED => 9600} );
  232.          $clear_string = $terminal->Tputs('cl');
  233.  
  234.  
  235.      HHHHoooowwww ddddoooo IIII ggggeeeetttt tttthhhheeee ssssccccrrrreeeeeeeennnn ssssiiiizzzzeeee????
  236.  
  237.      If you have Term::ReadKey module installed from CPAN, you can use it to
  238.      fetch the width and height in characters and in pixels:
  239.  
  240.          use Term::ReadKey;
  241.          ($wchar, $hchar, $wpixels, $hpixels) = GetTerminalSize();
  242.  
  243.      This is more portable than the raw ioctl, but not as illustrative:
  244.  
  245.          require 'sys/ioctl.ph';
  246.          die "no TIOCGWINSZ " unless defined &TIOCGWINSZ;
  247.          open(TTY, "+</dev/tty")                     or die "No tty: $!";
  248.          unless (ioctl(TTY, &TIOCGWINSZ, $winsize='')) {
  249.              die sprintf "$0: ioctl TIOCGWINSZ (%08x: $!)\n", &TIOCGWINSZ;
  250.          }
  251.          ($row, $col, $xpixel, $ypixel) = unpack('S4', $winsize);
  252.          print "(row,col) = ($row,$col)";
  253.          print "  (xpixel,ypixel) = ($xpixel,$ypixel)" if $xpixel || $ypixel;
  254.          print "\n";
  255.  
  256.  
  257.  
  258.  
  259.  
  260.  
  261.                                                                         PPPPaaaaggggeeee 4444
  262.  
  263.  
  264.  
  265.  
  266.  
  267.  
  268. PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))
  269.  
  270.  
  271.  
  272.      HHHHoooowwww ddddoooo IIII aaaasssskkkk tttthhhheeee uuuusssseeeerrrr ffffoooorrrr aaaa ppppaaaasssssssswwwwoooorrrrdddd????
  273.  
  274.      (This question has nothing to do with the web.  See a different FAQ for
  275.      that.)
  276.  
  277.      There's an example of this in the crypt entry in the _p_e_r_l_f_u_n_c manpage).
  278.      First, you put the terminal into "no echo" mode, then just read the
  279.      password normally.  You may do this with an old-style _i_o_c_t_l() function,
  280.      POSIX terminal control (see the _P_O_S_I_X manpage, and Chapter 7 of the
  281.      Camel), or a call to the ssssttttttttyyyy program, with varying degrees of
  282.      portability.
  283.  
  284.      You can also do this for most systems using the Term::ReadKey module from
  285.      CPAN, which is easier to use and in theory more portable.
  286.  
  287.          use Term::ReadKey;
  288.  
  289.          ReadMode('noecho');
  290.          $password = ReadLine(0);
  291.  
  292.  
  293.      HHHHoooowwww ddddoooo IIII rrrreeeeaaaadddd aaaannnndddd wwwwrrrriiiitttteeee tttthhhheeee sssseeeerrrriiiiaaaallll ppppoooorrrrtttt????
  294.  
  295.      This depends on which operating system your program is running on.  In
  296.      the case of Unix, the serial ports will be accessible through files in
  297.      /dev; on other systems, the devices names will doubtless differ.  Several
  298.      problem areas common to all device interaction are the following
  299.  
  300.      lockfiles
  301.          Your system may use lockfiles to control multiple access.  Make sure
  302.          you follow the correct protocol.  Unpredictable behaviour can result
  303.          from multiple processes reading from one device.
  304.  
  305.      open mode
  306.          If you expect to use both read and write operations on the device,
  307.          you'll have to open it for update (see the section on _o_p_e_n in the
  308.          _p_e_r_l_f_u_n_c manpage for details).  You may wish to open it without
  309.          running the risk of blocking by using _s_y_s_o_p_e_n() and
  310.          O_RDWR|O_NDELAY|O_NOCTTY from the Fcntl module (part of the standard
  311.          perl distribution).  See the section on _s_y_s_o_p_e_n in the _p_e_r_l_f_u_n_c
  312.          manpage for more on this approach.
  313.  
  314.      end of line
  315.          Some devices will be expecting a "\r" at the end of each line rather
  316.          than a "\n".  In some ports of perl, "\r" and "\n" are different from
  317.          their usual (Unix) ASCII values of "\012" and "\015".  You may have
  318.          to give the numeric values you want directly, using octal ("\015"),
  319.          hex ("0x0D"), or as a control-character specification ("\cM").
  320.  
  321.              print DEV "atv1\012";       # wrong, for some devices
  322.              print DEV "atv1\015";       # right, for some devices
  323.  
  324.  
  325.  
  326.  
  327.                                                                         PPPPaaaaggggeeee 5555
  328.  
  329.  
  330.  
  331.  
  332.  
  333.  
  334. PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))
  335.  
  336.  
  337.  
  338.          Even though with normal text files, a "\n" will do the trick, there
  339.          is still no unified scheme for terminating a line that is portable
  340.          between Unix, DOS/Win, and Macintosh, except to terminate _A_L_L line
  341.          ends with "\015\012", and strip what you don't need from the output.
  342.          This applies especially to socket I/O and autoflushing, discussed
  343.          next.
  344.  
  345.      flushing output
  346.          If you expect characters to get to your device when you _p_r_i_n_t() them,
  347.          you'll want to autoflush that filehandle.  You can use _s_e_l_e_c_t() and
  348.          the $| variable to control autoflushing (see the section on $| in the
  349.          _p_e_r_l_v_a_r manpage and the select entry in the _p_e_r_l_f_u_n_c manpage):
  350.  
  351.              $oldh = select(DEV);
  352.              $| = 1;
  353.              select($oldh);
  354.  
  355.          You'll also see code that does this without a temporary variable, as
  356.          in
  357.  
  358.              select((select(DEV), $| = 1)[0]);
  359.  
  360.          Or if you don't mind pulling in a few thousand lines of code just
  361.          because you're afraid of a little $| variable:
  362.  
  363.              use IO::Handle;
  364.              DEV->autoflush(1);
  365.  
  366.          As mentioned in the previous item, this still doesn't work when using
  367.          socket I/O between Unix and Macintosh.  You'll need to hardcode your
  368.          line terminators, in that case.
  369.  
  370.      non-blocking input
  371.          If you are doing a blocking _r_e_a_d() or _s_y_s_r_e_a_d(), you'll have to
  372.          arrange for an alarm handler to provide a timeout (see the alarm
  373.          entry in the _p_e_r_l_f_u_n_c manpage).  If you have a non-blocking open,
  374.          you'll likely have a non-blocking read, which means you may have to
  375.          use a 4-arg _s_e_l_e_c_t() to determine whether I/O is ready on that device
  376.          (see the section on _s_e_l_e_c_t in the _p_e_r_l_f_u_n_c manpage.
  377.  
  378.      While trying to read from his caller-id box, the notorious Jamie Zawinski
  379.      <jwz@netscape.com>, after much gnashing of teeth and fighting with
  380.      sysread, sysopen, POSIX's tcgetattr business, and various other functions
  381.      that go bump in the night, finally came up with this:
  382.  
  383.  
  384.  
  385.  
  386.  
  387.  
  388.  
  389.  
  390.  
  391.  
  392.  
  393.                                                                         PPPPaaaaggggeeee 6666
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400. PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))
  401.  
  402.  
  403.  
  404.          sub open_modem {
  405.              use IPC::Open2;
  406.              my $stty = `/bin/stty -g`;
  407.              open2( \*MODEM_IN, \*MODEM_OUT, "cu -l$modem_device -s2400 2>&1");
  408.              # starting cu hoses /dev/tty's stty settings, even when it has
  409.              # been opened on a pipe...
  410.              system("/bin/stty $stty");
  411.              $_ = <MODEM_IN>;
  412.              chop;
  413.              if ( !m/^Connected/ ) {
  414.                  print STDERR "$0: cu printed `$_' instead of `Connected'\n";
  415.              }
  416.          }
  417.  
  418.  
  419.      HHHHoooowwww ddddoooo IIII ddddeeeeccccooooddddeeee eeeennnnccccrrrryyyypppptttteeeedddd ppppaaaasssssssswwwwoooorrrrdddd ffffiiiilllleeeessss????
  420.  
  421.      You spend lots and lots of money on dedicated hardware, but this is bound
  422.      to get you talked about.
  423.  
  424.      Seriously, you can't if they are Unix password files - the Unix password
  425.      system employs one-way encryption.  It's more like hashing than
  426.      encryption.  The best you can check is whether something else hashes to
  427.      the same string.  You can't turn a hash back into the original string.
  428.      Programs like Crack can forcibly (and intelligently) try to guess
  429.      passwords, but don't (can't) guarantee quick success.
  430.  
  431.      If you're worried about users selecting bad passwords, you should
  432.      proactively check when they try to change their password (by modifying
  433.      _p_a_s_s_w_d(1), for example).
  434.  
  435.      HHHHoooowwww ddddoooo IIII ssssttttaaaarrrrtttt aaaa pppprrrroooocccceeeessssssss iiiinnnn tttthhhheeee bbbbaaaacccckkkkggggrrrroooouuuunnnndddd????
  436.  
  437.      You could use
  438.  
  439.          system("cmd &")
  440.  
  441.      or you could use fork as documented in the section on _f_o_r_k in the
  442.      _p_e_r_l_f_u_n_c manpage, with further examples in the _p_e_r_l_i_p_c manpage.  Some
  443.      things to be aware of, if you're on a Unix-like system:
  444.  
  445.      STDIN, STDOUT, and STDERR are shared
  446.          Both the main process and the backgrounded one (the "child" process)
  447.          share the same STDIN, STDOUT and STDERR filehandles.  If both try to
  448.          access them at once, strange things can happen.  You may want to
  449.          close or reopen these for the child.  You can get around this with
  450.          opening a pipe (see the section on _o_p_e_n in the _p_e_r_l_f_u_n_c manpage) but
  451.          on some systems this means that the child process cannot outlive the
  452.          parent.
  453.  
  454.  
  455.  
  456.  
  457.  
  458.  
  459.                                                                         PPPPaaaaggggeeee 7777
  460.  
  461.  
  462.  
  463.  
  464.  
  465.  
  466. PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))
  467.  
  468.  
  469.  
  470.      Signals
  471.          You'll have to catch the SIGCHLD signal, and possibly SIGPIPE too.
  472.          SIGCHLD is sent when the backgrounded process finishes.  SIGPIPE is
  473.          sent when you write to a filehandle whose child process has closed
  474.          (an untrapped SIGPIPE can cause your program to silently die).  This
  475.          is not an issue with system("cmd&").
  476.  
  477.      Zombies
  478.          You have to be prepared to "reap" the child process when it finishes
  479.  
  480.              $SIG{CHLD} = sub { wait };
  481.  
  482.          See the section on _S_i_g_n_a_l_s in the _p_e_r_l_i_p_c manpage for other examples
  483.          of code to do this.  Zombies are not an issue with system("prog &").
  484.  
  485.      HHHHoooowwww ddddoooo IIII ttttrrrraaaapppp ccccoooonnnnttttrrrroooollll cccchhhhaaaarrrraaaacccctttteeeerrrrssss////ssssiiiiggggnnnnaaaallllssss????
  486.  
  487.      You don't actually "trap" a control character.  Instead, that character
  488.      generates a signal which is sent to your terminal's currently
  489.      foregrounded process group, which you then trap in your process.  Signals
  490.      are documented in the section on _S_i_g_n_a_l_s in the _p_e_r_l_i_p_c manpage and
  491.      chapter 6 of the Camel.
  492.  
  493.      Be warned that very few C libraries are re-entrant.  Therefore, if you
  494.      attempt to _p_r_i_n_t() in a handler that got invoked during another stdio
  495.      operation your internal structures will likely be in an inconsistent
  496.      state, and your program will dump core.  You can sometimes avoid this by
  497.      using _s_y_s_w_r_i_t_e() instead of _p_r_i_n_t().
  498.  
  499.      Unless you're exceedingly careful, the only safe things to do inside a
  500.      signal handler are: set a variable and exit.  And in the first case, you
  501.      should only set a variable in such a way that _m_a_l_l_o_c() is not called (eg,
  502.      by setting a variable that already has a value).
  503.  
  504.      For example:
  505.  
  506.          $Interrupted = 0;   # to ensure it has a value
  507.          $SIG{INT} = sub {
  508.              $Interrupted++;
  509.              syswrite(STDERR, "ouch\n", 5);
  510.          }
  511.  
  512.      However, because syscalls restart by default, you'll find that if you're
  513.      in a "slow" call, such as <FH>, _r_e_a_d(), _c_o_n_n_e_c_t(), or _w_a_i_t(), that the
  514.      only way to terminate them is by "longjumping" out; that is, by raising
  515.      an exception.  See the time-out handler for a blocking _f_l_o_c_k() in the
  516.      section on _S_i_g_n_a_l_s in the _p_e_r_l_i_p_c manpage or chapter 6 of the Camel.
  517.  
  518.      HHHHoooowwww ddddoooo IIII mmmmooooddddiiiiffffyyyy tttthhhheeee sssshhhhaaaaddddoooowwww ppppaaaasssssssswwwwoooorrrrdddd ffffiiiilllleeee oooonnnn aaaa UUUUnnnniiiixxxx ssssyyyysssstttteeeemmmm????
  519.  
  520.  
  521.  
  522.  
  523.  
  524.  
  525.                                                                         PPPPaaaaggggeeee 8888
  526.  
  527.  
  528.  
  529.  
  530.  
  531.  
  532. PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))
  533.  
  534.  
  535.  
  536.      If perl was installed correctly, and your shadow library was written
  537.      properly, the getpw*() functions described in the _p_e_r_l_f_u_n_c manpage should
  538.      in theory provide (read-only) access to entries in the shadow password
  539.      file.  To change the file, make a new shadow password file (the format
  540.      varies from system to system - see the _p_a_s_s_w_d(_5) manpage for specifics)
  541.      and use _p_w_d__m_k_d_b(8) to install it (see the _p_w_d__m_k_d_b(_5) manpage for more
  542.      details).
  543.  
  544.      HHHHoooowwww ddddoooo IIII sssseeeetttt tttthhhheeee ttttiiiimmmmeeee aaaannnndddd ddddaaaatttteeee????
  545.  
  546.      Assuming you're running under sufficient permissions, you should be able
  547.      to set the system-wide date and time by running the _d_a_t_e(1) program.
  548.      (There is no way to set the time and date on a per-process basis.)  This
  549.      mechanism will work for Unix, MS-DOS, Windows, and NT; the VMS equivalent
  550.      is set time.
  551.  
  552.      However, if all you want to do is change your timezone, you can probably
  553.      get away with setting an environment variable:
  554.  
  555.          $ENV{TZ} = "MST7MDT";                  # unixish
  556.          $ENV{'SYS$TIMEZONE_DIFFERENTIAL'}="-5" # vms
  557.          system "trn comp.lang.perl.misc";
  558.  
  559.  
  560.      HHHHoooowwww ccccaaaannnn IIII _s_l_e_e_p() or _a_l_a_r_m() for under a second?
  561.  
  562.      If you want finer granularity than the 1 second that the _s_l_e_e_p() function
  563.      provides, the easiest way is to use the _s_e_l_e_c_t() function as documented
  564.      in the section on _s_e_l_e_c_t in the _p_e_r_l_f_u_n_c manpage.  If your system has
  565.      itimers and _s_y_s_c_a_l_l() support, you can check out the old example in
  566.      http://www.perl.com/CPAN/doc/misc/ancient/tutorial/eg/itimers.pl .
  567.  
  568.      HHHHoooowwww ccccaaaannnn IIII mmmmeeeeaaaassssuuuurrrreeee ttttiiiimmmmeeee uuuunnnnddddeeeerrrr aaaa sssseeeeccccoooonnnndddd????
  569.  
  570.      In general, you may not be able to.  The Time::HiRes module (available
  571.      from CPAN) provides this functionality for some systems.
  572.  
  573.      In general, you may not be able to.  But if your system supports both the
  574.      _s_y_s_c_a_l_l() function in Perl as well as a system call like _g_e_t_t_i_m_e_o_f_d_a_y(2),
  575.      then you may be able to do something like this:
  576.  
  577.          require 'sys/syscall.ph';
  578.  
  579.          $TIMEVAL_T = "LL";
  580.  
  581.          $done = $start = pack($TIMEVAL_T, ());
  582.  
  583.          syscall( &SYS_gettimeofday, $start, 0)) != -1
  584.                     or die "gettimeofday: $!";
  585.  
  586.  
  587.  
  588.  
  589.  
  590.  
  591.                                                                         PPPPaaaaggggeeee 9999
  592.  
  593.  
  594.  
  595.  
  596.  
  597.  
  598. PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))
  599.  
  600.  
  601.  
  602.             ##########################
  603.             # DO YOUR OPERATION HERE #
  604.             ##########################
  605.  
  606.          syscall( &SYS_gettimeofday, $done, 0) != -1
  607.                 or die "gettimeofday: $!";
  608.  
  609.          @start = unpack($TIMEVAL_T, $start);
  610.          @done  = unpack($TIMEVAL_T, $done);
  611.  
  612.          # fix microseconds
  613.          for ($done[1], $start[1]) { $_ /= 1_000_000 }
  614.  
  615.          $delta_time = sprintf "%.4f", ($done[0]  + $done[1]  )
  616.                                                  -
  617.                                       ($start[0] + $start[1] );
  618.  
  619.  
  620.      HHHHoooowwww ccccaaaannnn IIII ddddoooo aaaannnn _a_t_e_x_i_t() or _s_e_t_j_m_p()/_l_o_n_g_j_m_p()? (Exception handling)
  621.  
  622.      Release 5 of Perl added the END block, which can be used to simulate
  623.      _a_t_e_x_i_t().  Each package's END block is called when the program or thread
  624.      ends (see the _p_e_r_l_m_o_d manpage manpage for more details).
  625.  
  626.      For example, you can use this to make sure your filter program managed to
  627.      finish its output without filling up the disk:
  628.  
  629.          END {
  630.              close(STDOUT) || die "stdout close failed: $!";
  631.          }
  632.  
  633.      The END block isn't called when untrapped signals kill the program,
  634.      though, so if you use END blocks you should also use
  635.  
  636.              use sigtrap qw(die normal-signals);
  637.  
  638.      Perl's exception-handling mechanism is its _e_v_a_l() operator.  You can use
  639.      _e_v_a_l() as setjmp and _d_i_e() as longjmp.  For details of this, see the
  640.      section on signals, especially the time-out handler for a blocking
  641.      _f_l_o_c_k() in the section on _S_i_g_n_a_l_s in the _p_e_r_l_i_p_c manpage and chapter 6 of
  642.      the Camel.
  643.  
  644.      If exception handling is all you're interested in, try the exceptions.pl
  645.      library (part of the standard perl distribution).
  646.  
  647.      If you want the _a_t_e_x_i_t() syntax (and an _r_m_e_x_i_t() as well), try the AtExit
  648.      module available from CPAN.
  649.  
  650.      WWWWhhhhyyyy ddddooooeeeessssnnnn''''tttt mmmmyyyy ssssoooocccckkkkeeeettttssss pppprrrrooooggggrrrraaaammmm wwwwoooorrrrkkkk uuuunnnnddddeeeerrrr SSSSyyyysssstttteeeemmmm VVVV ((((SSSSoooollllaaaarrrriiiissss))))???? WWWWhhhhaaaatttt ddddooooeeeessss
  651.      tttthhhheeee eeeerrrrrrrroooorrrr mmmmeeeessssssssaaaaggggeeee """"PPPPrrrroooottttooooccccoooollll nnnnooootttt ssssuuuuppppppppoooorrrrtttteeeedddd"""" mmmmeeeeaaaannnn????
  652.  
  653.  
  654.  
  655.  
  656.  
  657.                                                                        PPPPaaaaggggeeee 11110000
  658.  
  659.  
  660.  
  661.  
  662.  
  663.  
  664. PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))
  665.  
  666.  
  667.  
  668.      Some Sys-V based systems, notably Solaris 2.X, redefined some of the
  669.      standard socket constants.  Since these were constant across all
  670.      architectures, they were often hardwired into perl code.  The proper way
  671.      to deal with this is to "use Socket" to get the correct values.
  672.  
  673.      Note that even though SunOS and Solaris are binary compatible, these
  674.      values are different.  Go figure.
  675.  
  676.      HHHHoooowwww ccccaaaannnn IIII ccccaaaallllllll mmmmyyyy ssssyyyysssstttteeeemmmm''''ssss uuuunnnniiiiqqqquuuueeee CCCC ffffuuuunnnnccccttttiiiioooonnnnssss ffffrrrroooommmm PPPPeeeerrrrllll????
  677.  
  678.      In most cases, you write an external module to do it - see the answer to
  679.      "Where can I learn about linking C with Perl? [h2xs, xsubpp]".  However,
  680.      if the function is a system call, and your system supports _s_y_s_c_a_l_l(), you
  681.      can use the syscall function (documented in the _p_e_r_l_f_u_n_c manpage).
  682.  
  683.      Remember to check the modules that came with your distribution, and CPAN
  684.      as well - someone may already have written a module to do it.
  685.  
  686.      WWWWhhhheeeerrrreeee ddddoooo IIII ggggeeeetttt tttthhhheeee iiiinnnncccclllluuuuddddeeee ffffiiiilllleeeessss ttttoooo ddddoooo _i_o_c_t_l() or _s_y_s_c_a_l_l()?
  687.  
  688.      Historically, these would be generated by the h2ph tool, part of the
  689.      standard perl distribution.  This program converts _c_p_p(1) directives in C
  690.      header files to files containing subroutine definitions, like
  691.      &SYS_getitimer, which you can use as arguments to your functions.  It
  692.      doesn't work perfectly, but it usually gets most of the job done.  Simple
  693.      files like _e_r_r_n_o._h, _s_y_s_c_a_l_l._h, and _s_o_c_k_e_t._h were fine, but the hard ones
  694.      like _i_o_c_t_l._h nearly always need to hand-edited.  Here's how to install
  695.      the *.ph files:
  696.  
  697.          1.  become super-user
  698.          2.  cd /usr/include
  699.          3.  h2ph *.h */*.h
  700.  
  701.      If your system supports dynamic loading, for reasons of portability and
  702.      sanity you probably ought to use h2xs (also part of the standard perl
  703.      distribution).  This tool converts C header files to Perl extensions.
  704.      See the _p_e_r_l_x_s_t_u_t manpage for how to get started with h2xs.
  705.  
  706.      If your system doesn't support dynamic loading, you still probably ought
  707.      to use h2xs.  See the _p_e_r_l_x_s_t_u_t manpage and the _E_x_t_U_t_i_l_s::_M_a_k_e_M_a_k_e_r
  708.      manpage for more information (in brief, just use mmmmaaaakkkkeeee ppppeeeerrrrllll instead of a
  709.      plain mmmmaaaakkkkeeee to rebuild perl with a new static extension).
  710.  
  711.      WWWWhhhhyyyy ddddoooo sssseeeettttuuuuiiiidddd ppppeeeerrrrllll ssssccccrrrriiiippppttttssss ccccoooommmmppppllllaaaaiiiinnnn aaaabbbboooouuuutttt kkkkeeeerrrrnnnneeeellll pppprrrroooobbbblllleeeemmmmssss????
  712.  
  713.      Some operating systems have bugs in the kernel that make setuid scripts
  714.      inherently insecure.  Perl gives you a number of options (described in
  715.      the _p_e_r_l_s_e_c manpage) to work around such systems.
  716.  
  717.  
  718.  
  719.  
  720.  
  721.  
  722.  
  723.                                                                        PPPPaaaaggggeeee 11111111
  724.  
  725.  
  726.  
  727.  
  728.  
  729.  
  730. PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))
  731.  
  732.  
  733.  
  734.      HHHHoooowwww ccccaaaannnn IIII ooooppppeeeennnn aaaa ppppiiiippppeeee bbbbooootttthhhh ttttoooo aaaannnndddd ffffrrrroooommmm aaaa ccccoooommmmmmmmaaaannnndddd????
  735.  
  736.      The IPC::Open2 module (part of the standard perl distribution) is an
  737.      easy-to-use approach that internally uses _p_i_p_e(), _f_o_r_k(), and _e_x_e_c() to
  738.      do the job.  Make sure you read the deadlock warnings in its
  739.      documentation, though (see the _I_P_C::_O_p_e_n_2 manpage).  See the section on
  740.      _B_i_d_i_r_e_c_t_i_o_n_a_l _C_o_m_m_u_n_i_c_a_t_i_o_n _w_i_t_h _A_n_o_t_h_e_r _P_r_o_c_e_s_s in the _p_e_r_l_i_p_c manpage
  741.      and the section on _B_i_d_i_r_e_c_t_i_o_n_a_l _C_o_m_m_u_n_i_c_a_t_i_o_n _w_i_t_h _Y_o_u_r_s_e_l_f in the
  742.      _p_e_r_l_i_p_c manpage
  743.  
  744.      You may also use the IPC::Open3 module (part of the standard perl
  745.      distribution), but be warned that it has a different order of arguments
  746.      from IPC::Open2 (see the _I_P_C::_O_p_e_n_3 manpage).
  747.  
  748.      WWWWhhhhyyyy ccccaaaannnn''''tttt IIII ggggeeeetttt tttthhhheeee oooouuuuttttppppuuuutttt ooooffff aaaa ccccoooommmmmmmmaaaannnndddd wwwwiiiitttthhhh _s_y_s_t_e_m()?
  749.  
  750.      You're confusing the purpose of _s_y_s_t_e_m() and backticks (``).  _s_y_s_t_e_m()
  751.      runs a command and returns exit status information (as a 16 bit value:
  752.      the low 7 bits are the signal the process died from, if any, and the high
  753.      8 bits are the actual exit value).  Backticks (``) run a command and
  754.      return what it sent to STDOUT.
  755.  
  756.          $exit_status   = system("mail-users");
  757.          $output_string = `ls`;
  758.  
  759.  
  760.      HHHHoooowwww ccccaaaannnn IIII ccccaaaappppttttuuuurrrreeee SSSSTTTTDDDDEEEERRRRRRRR ffffrrrroooommmm aaaannnn eeeexxxxtttteeeerrrrnnnnaaaallll ccccoooommmmmmmmaaaannnndddd????
  761.  
  762.      There are three basic ways of running external commands:
  763.  
  764.          system $cmd;                # using system()
  765.          $output = `$cmd`;           # using backticks (``)
  766.          open (PIPE, "cmd |");       # using open()
  767.  
  768.      With _s_y_s_t_e_m(), both STDOUT and STDERR will go the same place as the
  769.      script's versions of these, unless the command redirects them.  Backticks
  770.      and _o_p_e_n() read oooonnnnllllyyyy the STDOUT of your command.
  771.  
  772.      With any of these, you can change file descriptors before the call:
  773.  
  774.          open(STDOUT, ">logfile");
  775.          system("ls");
  776.  
  777.      or you can use Bourne shell file-descriptor redirection:
  778.  
  779.          $output = `$cmd 2>some_file`;
  780.          open (PIPE, "cmd 2>some_file |");
  781.  
  782.      You can also use file-descriptor redirection to make STDERR a duplicate
  783.      of STDOUT:
  784.  
  785.  
  786.  
  787.  
  788.  
  789.                                                                        PPPPaaaaggggeeee 11112222
  790.  
  791.  
  792.  
  793.  
  794.  
  795.  
  796. PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))
  797.  
  798.  
  799.  
  800.          $output = `$cmd 2>&1`;
  801.          open (PIPE, "cmd 2>&1 |");
  802.  
  803.      Note that you _c_a_n_n_o_t simply open STDERR to be a dup of STDOUT in your
  804.      Perl program and avoid calling the shell to do the redirection.  This
  805.      doesn't work:
  806.  
  807.          open(STDERR, ">&STDOUT");
  808.          $alloutput = `cmd args`;  # stderr still escapes
  809.  
  810.      This fails because the _o_p_e_n() makes STDERR go to where STDOUT was going
  811.      at the time of the _o_p_e_n().  The backticks then make STDOUT go to a
  812.      string, but don't change STDERR (which still goes to the old STDOUT).
  813.  
  814.      Note that you _m_u_s_t use Bourne shell (_s_h(1)) redirection syntax in
  815.      backticks, not _c_s_h(1)!  Details on why Perl's _s_y_s_t_e_m() and backtick and
  816.      pipe opens all use the Bourne shell are in
  817.      http://www.perl.com/CPAN/doc/FMTEYEWTK/versus/csh.whynot .  To capture a
  818.      command's STDERR and STDOUT together:
  819.  
  820.          $output = `cmd 2>&1`;                       # either with backticks
  821.          $pid = open(PH, "cmd 2>&1 |");              # or with an open pipe
  822.          while (<PH>) { }                            #    plus a read
  823.  
  824.      To capture a command's STDOUT but discard its STDERR:
  825.  
  826.          $output = `cmd 2>/dev/null`;                # either with backticks
  827.          $pid = open(PH, "cmd 2>/dev/null |");       # or with an open pipe
  828.          while (<PH>) { }                            #    plus a read
  829.  
  830.      To capture a command's STDERR but discard its STDOUT:
  831.  
  832.          $output = `cmd 2>&1 1>/dev/null`;           # either with backticks
  833.          $pid = open(PH, "cmd 2>&1 1>/dev/null |");  # or with an open pipe
  834.          while (<PH>) { }                            #    plus a read
  835.  
  836.      To exchange a command's STDOUT and STDERR in order to capture the STDERR
  837.      but leave its STDOUT to come out our old STDERR:
  838.  
  839.          $output = `cmd 3>&1 1>&2 2>&3 3>&-`;        # either with backticks
  840.          $pid = open(PH, "cmd 3>&1 1>&2 2>&3 3>&-|");# or with an open pipe
  841.          while (<PH>) { }                            #    plus a read
  842.  
  843.      To read both a command's STDOUT and its STDERR separately, it's easiest
  844.      and safest to redirect them separately to files, and then read from those
  845.      files when the program is done:
  846.  
  847.          system("program args 1>/tmp/program.stdout 2>/tmp/program.stderr");
  848.  
  849.      Ordering is important in all these examples.  That's because the shell
  850.      processes file descriptor redirections in strictly left to right order.
  851.  
  852.  
  853.  
  854.  
  855.                                                                        PPPPaaaaggggeeee 11113333
  856.  
  857.  
  858.  
  859.  
  860.  
  861.  
  862. PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))
  863.  
  864.  
  865.  
  866.          system("prog args 1>tmpfile 2>&1");
  867.          system("prog args 2>&1 1>tmpfile");
  868.  
  869.      The first command sends both standard out and standard error to the
  870.      temporary file.  The second command sends only the old standard output
  871.      there, and the old standard error shows up on the old standard out.
  872.  
  873.      WWWWhhhhyyyy ddddooooeeeessssnnnn''''tttt _o_p_e_n() return an error when a pipe open fails?
  874.  
  875.      It does, but probably not how you expect it to.  On systems that follow
  876.      the standard _f_o_r_k()/_e_x_e_c() paradigm (such as Unix), it works like this:
  877.      _o_p_e_n() causes a _f_o_r_k().  In the parent, _o_p_e_n() returns with the process
  878.      ID of the child.  The child _e_x_e_c()s the command to be piped to/from.  The
  879.      parent can't know whether the _e_x_e_c() was successful or not - all it can
  880.      return is whether the _f_o_r_k() succeeded or not.  To find out if the
  881.      command succeeded, you have to catch SIGCHLD and _w_a_i_t() to get the exit
  882.      status.  You should also catch SIGPIPE if you're writing to the child --
  883.      you may not have found out the _e_x_e_c() failed by the time you write.  This
  884.      is documented in the _p_e_r_l_i_p_c manpage.
  885.  
  886.      On systems that follow the _s_p_a_w_n() paradigm, _o_p_e_n() _m_i_g_h_t do what you
  887.      expect - unless perl uses a shell to start your command. In this case the
  888.      _f_o_r_k()/_e_x_e_c() description still applies.
  889.  
  890.      WWWWhhhhaaaatttt''''ssss wwwwrrrroooonnnngggg wwwwiiiitttthhhh uuuussssiiiinnnngggg bbbbaaaacccckkkkttttiiiicccckkkkssss iiiinnnn aaaa vvvvooooiiiidddd ccccoooonnnntttteeeexxxxtttt????
  891.  
  892.      Strictly speaking, nothing.  Stylistically speaking, it's not a good way
  893.      to write maintainable code because backticks have a (potentially
  894.      humungous) return value, and you're ignoring it.  It's may also not be
  895.      very efficient, because you have to read in all the lines of output,
  896.      allocate memory for them, and then throw it away.  Too often people are
  897.      lulled to writing:
  898.  
  899.          `cp file file.bak`;
  900.  
  901.      And now they think "Hey, I'll just always use backticks to run programs."
  902.      Bad idea: backticks are for capturing a program's output; the _s_y_s_t_e_m()
  903.      function is for running programs.
  904.  
  905.      Consider this line:
  906.  
  907.          `cat /etc/termcap`;
  908.  
  909.      You haven't assigned the output anywhere, so it just wastes memory (for a
  910.      little while).  Plus you forgot to check $? to see whether the program
  911.      even ran correctly.  Even if you wrote
  912.  
  913.          print `cat /etc/termcap`;
  914.  
  915.      In most cases, this could and probably should be written as
  916.  
  917.  
  918.  
  919.  
  920.  
  921.                                                                        PPPPaaaaggggeeee 11114444
  922.  
  923.  
  924.  
  925.  
  926.  
  927.  
  928. PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))
  929.  
  930.  
  931.  
  932.          system("cat /etc/termcap") == 0
  933.              or die "cat program failed!";
  934.  
  935.      Which will get the output quickly (as its generated, instead of only at
  936.      the end) and also check the return value.
  937.  
  938.      _s_y_s_t_e_m() also provides direct control over whether shell wildcard
  939.      processing may take place, whereas backticks do not.
  940.  
  941.      HHHHoooowwww ccccaaaannnn IIII ccccaaaallllllll bbbbaaaacccckkkkttttiiiicccckkkkssss wwwwiiiitttthhhhoooouuuutttt sssshhhheeeellllllll pppprrrroooocccceeeessssssssiiiinnnngggg????
  942.  
  943.      This is a bit tricky.  Instead of writing
  944.  
  945.          @ok = `grep @opts '$search_string' @filenames`;
  946.  
  947.      You have to do this:
  948.  
  949.          my @ok = ();
  950.          if (open(GREP, "-|")) {
  951.              while (<GREP>) {
  952.                  chomp;
  953.                  push(@ok, $_);
  954.              }
  955.              close GREP;
  956.          } else {
  957.              exec 'grep', @opts, $search_string, @filenames;
  958.          }
  959.  
  960.      Just as with _s_y_s_t_e_m(), no shell escapes happen when you _e_x_e_c() a list.
  961.  
  962.      There are more examples of this the section on _S_a_f_e _P_i_p_e _O_p_e_n_s in the
  963.      _p_e_r_l_i_p_c manpage.
  964.  
  965.      WWWWhhhhyyyy ccccaaaannnn''''tttt mmmmyyyy ssssccccrrrriiiipppptttt rrrreeeeaaaadddd ffffrrrroooommmm SSSSTTTTDDDDIIIINNNN aaaafffftttteeeerrrr IIII ggggaaaavvvveeee iiiitttt EEEEOOOOFFFF ((((^^^^DDDD oooonnnn UUUUnnnniiiixxxx,,,, ^^^^ZZZZ
  966.      oooonnnn MMMMSSSS----DDDDOOOOSSSS))))????
  967.  
  968.      Because some stdio's set error and eof flags that need clearing.  The
  969.      POSIX module defines _c_l_e_a_r_e_r_r() that you can use.  That is the
  970.      technically correct way to do it.  Here are some less reliable
  971.      workarounds:
  972.  
  973.      1   Try keeping around the seekpointer and go there, like this:
  974.  
  975.              $where = tell(LOG);
  976.              seek(LOG, $where, 0);
  977.  
  978.  
  979.      2   If that doesn't work, try seeking to a different part of the file and
  980.          then back.
  981.  
  982.  
  983.  
  984.  
  985.  
  986.  
  987.                                                                        PPPPaaaaggggeeee 11115555
  988.  
  989.  
  990.  
  991.  
  992.  
  993.  
  994. PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))
  995.  
  996.  
  997.  
  998.      3   If that doesn't work, try seeking to a different part of the file,
  999.          reading something, and then seeking back.
  1000.  
  1001.      4   If that doesn't work, give up on your stdio package and use sysread.
  1002.  
  1003.      HHHHoooowwww ccccaaaannnn IIII ccccoooonnnnvvvveeeerrrrtttt mmmmyyyy sssshhhheeeellllllll ssssccccrrrriiiipppptttt ttttoooo ppppeeeerrrrllll????
  1004.  
  1005.      Learn Perl and rewrite it.  Seriously, there's no simple converter.
  1006.      Things that are awkward to do in the shell are easy to do in Perl, and
  1007.      this very awkwardness is what would make a shell->perl converter nigh-on
  1008.      impossible to write.  By rewriting it, you'll think about what you're
  1009.      really trying to do, and hopefully will escape the shell's pipeline
  1010.      datastream paradigm, which while convenient for some matters, causes many
  1011.      inefficiencies.
  1012.  
  1013.      CCCCaaaannnn IIII uuuusssseeee ppppeeeerrrrllll ttttoooo rrrruuuunnnn aaaa tttteeeellllnnnneeeetttt oooorrrr ffffttttpppp sssseeeessssssssiiiioooonnnn????
  1014.  
  1015.      Try the Net::FTP, TCP::Client, and Net::Telnet modules (available from
  1016.      CPAN).  http://www.perl.com/CPAN/scripts/netstuff/telnet.emul.shar will
  1017.      also help for emulating the telnet protocol, but Net::Telnet is quite
  1018.      probably easier to use..
  1019.  
  1020.      If all you want to do is pretend to be telnet but don't need the initial
  1021.      telnet handshaking, then the standard dual-process approach will suffice:
  1022.  
  1023.          use IO::Socket;             # new in 5.004
  1024.          $handle = IO::Socket::INET->new('www.perl.com:80')
  1025.                  || die "can't connect to port 80 on www.perl.com: $!";
  1026.          $handle->autoflush(1);
  1027.          if (fork()) {               # XXX: undef means failure
  1028.              select($handle);
  1029.              print while <STDIN>;    # everything from stdin to socket
  1030.          } else {
  1031.              print while <$handle>;  # everything from socket to stdout
  1032.          }
  1033.          close $handle;
  1034.          exit;
  1035.  
  1036.  
  1037.      HHHHoooowwww ccccaaaannnn IIII wwwwrrrriiiitttteeee eeeexxxxppppeeeecccctttt iiiinnnn PPPPeeeerrrrllll????
  1038.  
  1039.      Once upon a time, there was a library called chat2.pl (part of the
  1040.      standard perl distribution), which never really got finished.  If you
  1041.      find it somewhere, _d_o_n'_t _u_s_e _i_t.  These days, your best bet is to look at
  1042.      the Expect module available from CPAN, which also requires two other
  1043.      modules from CPAN, IO::Pty and IO::Stty.
  1044.  
  1045.      IIIIssss tttthhhheeeerrrreeee aaaa wwwwaaaayyyy ttttoooo hhhhiiiiddddeeee ppppeeeerrrrllll''''ssss ccccoooommmmmmmmaaaannnndddd lllliiiinnnneeee ffffrrrroooommmm pppprrrrooooggggrrrraaaammmmssss ssssuuuucccchhhh aaaassss """"ppppssss""""????
  1046.  
  1047.      First of all note that if you're doing this for security reasons (to
  1048.      avoid people seeing passwords, for example) then you should rewrite your
  1049.      program so that critical information is never given as an argument.
  1050.  
  1051.  
  1052.  
  1053.                                                                        PPPPaaaaggggeeee 11116666
  1054.  
  1055.  
  1056.  
  1057.  
  1058.  
  1059.  
  1060. PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))
  1061.  
  1062.  
  1063.  
  1064.      Hiding the arguments won't make your program completely secure.
  1065.  
  1066.      To actually alter the visible command line, you can assign to the
  1067.      variable $0 as documented in the _p_e_r_l_v_a_r manpage.  This won't work on all
  1068.      operating systems, though.  Daemon programs like sendmail place their
  1069.      state there, as in:
  1070.  
  1071.          $0 = "orcus [accepting connections]";
  1072.  
  1073.  
  1074.      IIII {{{{cccchhhhaaaannnnggggeeeedddd ddddiiiirrrreeeeccccttttoooorrrryyyy,,,, mmmmooooddddiiiiffffiiiieeeedddd mmmmyyyy eeeennnnvvvviiiirrrroooonnnnmmmmeeeennnntttt}}}} iiiinnnn aaaa ppppeeeerrrrllll ssssccccrrrriiiipppptttt....  HHHHoooowwww
  1075.      ccccoooommmmeeee tttthhhheeee cccchhhhaaaannnnggggeeee ddddiiiissssaaaappppppppeeeeaaaarrrreeeedddd wwwwhhhheeeennnn IIII eeeexxxxiiiitttteeeedddd tttthhhheeee ssssccccrrrriiiipppptttt????  HHHHoooowwww ddddoooo IIII ggggeeeetttt mmmmyyyy
  1076.      cccchhhhaaaannnnggggeeeessss ttttoooo bbbbeeee vvvviiiissssiiiibbbblllleeee????
  1077.  
  1078.      Unix
  1079.          In the strictest sense, it can't be done -- the script executes as a
  1080.          different process from the shell it was started from.  Changes to a
  1081.          process are not reflected in its parent, only in its own children
  1082.          created after the change.  There is shell magic that may allow you to
  1083.          fake it by _e_v_a_l()ing the script's output in your shell; check out the
  1084.          comp.unix.questions FAQ for details.
  1085.  
  1086.      HHHHoooowwww ddddoooo IIII cccclllloooosssseeee aaaa pppprrrroooocccceeeessssssss''''ssss ffffiiiilllleeeehhhhaaaannnnddddlllleeee wwwwiiiitttthhhhoooouuuutttt wwwwaaaaiiiittttiiiinnnngggg ffffoooorrrr iiiitttt ttttoooo ccccoooommmmpppplllleeeetttteeee????
  1087.  
  1088.      Assuming your system supports such things, just send an appropriate
  1089.      signal to the process (see the section on _k_i_l_l in the _p_e_r_l_f_u_n_c manpage.
  1090.      It's common to first send a TERM signal, wait a little bit, and then send
  1091.      a KILL signal to finish it off.
  1092.  
  1093.      HHHHoooowwww ddddoooo IIII ffffoooorrrrkkkk aaaa ddddaaaaeeeemmmmoooonnnn pppprrrroooocccceeeessssssss????
  1094.  
  1095.      If by daemon process you mean one that's detached (disassociated from its
  1096.      tty), then the following process is reported to work on most Unixish
  1097.      systems.  Non-Unix users should check their Your_OS::Process module for
  1098.      other solutions.
  1099.  
  1100.      +o   Open /dev/tty and use the the TIOCNOTTY ioctl on it.  See the _t_t_y(_4)
  1101.          manpage for details.  Or better yet, you can just use the
  1102.          _P_O_S_I_X::_s_e_t_s_i_d() function, so you don't have to worry about process
  1103.          groups.
  1104.  
  1105.      +o   Change directory to /
  1106.  
  1107.      +o   Reopen STDIN, STDOUT, and STDERR so they're not connected to the old
  1108.          tty.
  1109.  
  1110.      +o   Background yourself like this:
  1111.  
  1112.              fork && exit;
  1113.  
  1114.  
  1115.  
  1116.  
  1117.  
  1118.  
  1119.                                                                        PPPPaaaaggggeeee 11117777
  1120.  
  1121.  
  1122.  
  1123.  
  1124.  
  1125.  
  1126. PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))
  1127.  
  1128.  
  1129.  
  1130.      HHHHoooowwww ddddoooo IIII mmmmaaaakkkkeeee mmmmyyyy pppprrrrooooggggrrrraaaammmm rrrruuuunnnn wwwwiiiitttthhhh sssshhhh aaaannnndddd ccccsssshhhh????
  1131.  
  1132.      See the _e_g/_n_i_h script (part of the perl source distribution).
  1133.  
  1134.      HHHHoooowwww ddddoooo IIII ffffiiiinnnndddd oooouuuutttt iiiiffff IIII''''mmmm rrrruuuunnnnnnnniiiinnnngggg iiiinnnntttteeeerrrraaaaccccttttiiiivvvveeeellllyyyy oooorrrr nnnnooootttt????
  1135.  
  1136.      Good question.  Sometimes -t STDIN and -t STDOUT can give clues,
  1137.      sometimes not.
  1138.  
  1139.          if (-t STDIN && -t STDOUT) {
  1140.              print "Now what? ";
  1141.          }
  1142.  
  1143.      On POSIX systems, you can test whether your own process group matches the
  1144.      current process group of your controlling terminal as follows:
  1145.  
  1146.          use POSIX qw/getpgrp tcgetpgrp/;
  1147.          open(TTY, "/dev/tty") or die $!;
  1148.          $tpgrp = tcgetpgrp(TTY);
  1149.          $pgrp = getpgrp();
  1150.          if ($tpgrp == $pgrp) {
  1151.              print "foreground\n";
  1152.          } else {
  1153.              print "background\n";
  1154.          }
  1155.  
  1156.  
  1157.      HHHHoooowwww ddddoooo IIII ttttiiiimmmmeeeeoooouuuutttt aaaa sssslllloooowwww eeeevvvveeeennnntttt????
  1158.  
  1159.      Use the _a_l_a_r_m() function, probably in conjunction with a signal handler,
  1160.      as documented the section on _S_i_g_n_a_l_s in the _p_e_r_l_i_p_c manpage and chapter 6
  1161.      of the Camel.  You may instead use the more flexible Sys::AlarmCall
  1162.      module available from CPAN.
  1163.  
  1164.      HHHHoooowwww ddddoooo IIII sssseeeetttt CCCCPPPPUUUU lllliiiimmmmiiiittttssss????
  1165.  
  1166.      Use the BSD::Resource module from CPAN.
  1167.  
  1168.      HHHHoooowwww ddddoooo IIII aaaavvvvooooiiiidddd zzzzoooommmmbbbbiiiieeeessss oooonnnn aaaa UUUUnnnniiiixxxx ssssyyyysssstttteeeemmmm????
  1169.  
  1170.      Use the reaper code from the section on _S_i_g_n_a_l_s in the _p_e_r_l_i_p_c manpage to
  1171.      call _w_a_i_t() when a SIGCHLD is received, or else use the double-fork
  1172.      technique described in the fork entry in the _p_e_r_l_f_u_n_c manpage.
  1173.  
  1174.      HHHHoooowwww ddddoooo IIII uuuusssseeee aaaannnn SSSSQQQQLLLL ddddaaaattttaaaabbbbaaaasssseeee????
  1175.  
  1176.      There are a number of excellent interfaces to SQL databases.  See the
  1177.      DBD::* modules available from http://www.perl.com/CPAN/modules/dbperl/DBD
  1178.      .  A lot of information on this can be found at
  1179.      http://www.hermetica.com/technologia/perl/DBI/index.html .
  1180.  
  1181.  
  1182.  
  1183.  
  1184.  
  1185.                                                                        PPPPaaaaggggeeee 11118888
  1186.  
  1187.  
  1188.  
  1189.  
  1190.  
  1191.  
  1192. PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))
  1193.  
  1194.  
  1195.  
  1196.      HHHHoooowwww ddddoooo IIII mmmmaaaakkkkeeee aaaa _s_y_s_t_e_m() exit on control-C?
  1197.  
  1198.      You can't.  You need to imitate the _s_y_s_t_e_m() call (see the _p_e_r_l_i_p_c
  1199.      manpage for sample code) and then have a signal handler for the INT
  1200.      signal that passes the signal on to the subprocess.  Or you can check for
  1201.      it:
  1202.  
  1203.          $rc = system($cmd);
  1204.          if ($rc & 127) { die "signal death" }
  1205.  
  1206.  
  1207.      HHHHoooowwww ddddoooo IIII ooooppppeeeennnn aaaa ffffiiiilllleeee wwwwiiiitttthhhhoooouuuutttt bbbblllloooocccckkkkiiiinnnngggg????
  1208.  
  1209.      If you're lucky enough to be using a system that supports non-blocking
  1210.      reads (most Unixish systems do), you need only to use the O_NDELAY or
  1211.      O_NONBLOCK flag from the Fcntl module in conjunction with _s_y_s_o_p_e_n():
  1212.  
  1213.          use Fcntl;
  1214.          sysopen(FH, "/tmp/somefile", O_WRONLY|O_NDELAY|O_CREAT, 0644)
  1215.              or die "can't open /tmp/somefile: $!":
  1216.  
  1217.  
  1218.      HHHHoooowwww ddddoooo IIII iiiinnnnssssttttaaaallllllll aaaa CCCCPPPPAAAANNNN mmmmoooodddduuuulllleeee????
  1219.  
  1220.      The easiest way is to have the CPAN module do it for you.  This module
  1221.      comes with perl version 5.004 and later.  To manually install the CPAN
  1222.      module, or any well-behaved CPAN module for that matter, follow these
  1223.      steps:
  1224.  
  1225.      1   Unpack the source into a temporary area.
  1226.  
  1227.      2
  1228.  
  1229.              perl Makefile.PL
  1230.  
  1231.  
  1232.      3
  1233.  
  1234.              make
  1235.  
  1236.  
  1237.      4
  1238.  
  1239.              make test
  1240.  
  1241.  
  1242.      5
  1243.  
  1244.              make install
  1245.  
  1246.  
  1247.  
  1248.  
  1249.  
  1250.  
  1251.                                                                        PPPPaaaaggggeeee 11119999
  1252.  
  1253.  
  1254.  
  1255.  
  1256.  
  1257.  
  1258. PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))
  1259.  
  1260.  
  1261.  
  1262.      If your version of perl is compiled without dynamic loading, then you
  1263.      just need to replace step 3 (mmmmaaaakkkkeeee) with mmmmaaaakkkkeeee ppppeeeerrrrllll and you will get a new
  1264.      _p_e_r_l binary with your extension linked in.
  1265.  
  1266.      See the _E_x_t_U_t_i_l_s::_M_a_k_e_M_a_k_e_r manpage for more details on building
  1267.      extensions.  See also the next question.
  1268.  
  1269.      WWWWhhhhaaaatttt''''ssss tttthhhheeee ddddiiiiffffffffeeeerrrreeeennnncccceeee bbbbeeeettttwwwweeeeeeeennnn rrrreeeeqqqquuuuiiiirrrreeee aaaannnndddd uuuusssseeee????
  1270.  
  1271.      Perl offers several different ways to include code from one file into
  1272.      another.  Here are the deltas between the various inclusion constructs:
  1273.  
  1274.          1)  do $file is like eval `cat $file`, except the former:
  1275.              1.1: searches @INC and updates %INC.
  1276.              1.2: bequeaths an *unrelated* lexical scope on the eval'ed code.
  1277.  
  1278.          2)  require $file is like do $file, except the former:
  1279.              2.1: checks for redundant loading, skipping already loaded files.
  1280.              2.2: raises an exception on failure to find, compile, or execute $file.
  1281.  
  1282.          3)  require Module is like require "Module.pm", except the former:
  1283.              3.1: translates each "::" into your system's directory separator.
  1284.              3.2: primes the parser to disambiguate class Module as an indirect object.
  1285.  
  1286.          4)  use Module is like require Module, except the former:
  1287.              4.1: loads the module at compile time, not run-time.
  1288.              4.2: imports symbols and semantics from that package to the current one.
  1289.  
  1290.      In general, you usually want use and a proper Perl module.
  1291.  
  1292.      HHHHoooowwww ddddoooo IIII kkkkeeeeeeeepppp mmmmyyyy oooowwwwnnnn mmmmoooodddduuuulllleeee////lllliiiibbbbrrrraaaarrrryyyy ddddiiiirrrreeeeccccttttoooorrrryyyy????
  1293.  
  1294.      When you build modules, use the PREFIX option when generating Makefiles:
  1295.  
  1296.          perl Makefile.PL PREFIX=/u/mydir/perl
  1297.  
  1298.      then either set the PERL5LIB environment variable before you run scripts
  1299.      that use the modules/libraries (see the _p_e_r_l_r_u_n manpage) or say
  1300.  
  1301.          use lib '/u/mydir/perl';
  1302.  
  1303.      See Perl's the _l_i_b manpage for more information.
  1304.  
  1305.      HHHHoooowwww ddddoooo IIII aaaadddddddd tttthhhheeee ddddiiiirrrreeeeccccttttoooorrrryyyy mmmmyyyy pppprrrrooooggggrrrraaaammmm lllliiiivvvveeeessss iiiinnnn ttttoooo tttthhhheeee mmmmoooodddduuuulllleeee////lllliiiibbbbrrrraaaarrrryyyy
  1306.      sssseeeeaaaarrrrcccchhhh ppppaaaatttthhhh????
  1307.  
  1308.          use FindBin;
  1309.          use lib "$FindBin::Bin";
  1310.          use your_own_modules;
  1311.  
  1312.  
  1313.  
  1314.  
  1315.  
  1316.  
  1317.                                                                        PPPPaaaaggggeeee 22220000
  1318.  
  1319.  
  1320.  
  1321.  
  1322.  
  1323.  
  1324. PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))
  1325.  
  1326.  
  1327.  
  1328.      HHHHoooowwww ddddoooo IIII aaaadddddddd aaaa ddddiiiirrrreeeeccccttttoooorrrryyyy ttttoooo mmmmyyyy iiiinnnncccclllluuuuddddeeee ppppaaaatttthhhh aaaatttt rrrruuuunnnnttttiiiimmmmeeee????
  1329.  
  1330.      Here are the suggested ways of modifying your include path:
  1331.  
  1332.          the PERLLIB environment variable
  1333.          the PERL5LIB environment variable
  1334.          the perl -Idir commpand line flag
  1335.          the use lib pragma, as in
  1336.              use lib "$ENV{HOME}/myown_perllib";
  1337.  
  1338.      The latter is particularly useful because it knows about machine
  1339.      dependent architectures.  The lib.pm pragmatic module was first included
  1340.      with the 5.002 release of Perl.
  1341.  
  1342. AAAAUUUUTTTTHHHHOOOORRRR AAAANNNNDDDD CCCCOOOOPPPPYYYYRRRRIIIIGGGGHHHHTTTT
  1343.      Copyright (c) 1997, 1998 Tom Christiansen and Nathan Torkington.  All
  1344.      rights reserved.
  1345.  
  1346.      When included as part of the Standard Version of Perl, or as part of its
  1347.      complete documentation whether printed or otherwise, this work may be
  1348.      distributed only under the terms of Perl's Artistic License.  Any
  1349.      distribution of this file or derivatives thereof _o_u_t_s_i_d_e of that package
  1350.      require that special arrangements be made with copyright holder.
  1351.  
  1352.      Irrespective of its distribution, all code examples in this file are
  1353.      hereby placed into the public domain.  You are permitted and encouraged
  1354.      to use this code in your own programs for fun or for profit as you see
  1355.      fit.  A simple comment in the code giving credit would be courteous but
  1356.      is not required.
  1357.  
  1358.  
  1359.  
  1360.  
  1361.  
  1362.  
  1363.  
  1364.  
  1365.  
  1366.  
  1367.  
  1368.  
  1369.  
  1370.  
  1371.  
  1372.  
  1373.  
  1374.  
  1375.  
  1376.  
  1377.  
  1378.  
  1379.  
  1380.  
  1381.  
  1382.  
  1383.                                                                        PPPPaaaaggggeeee 22221111
  1384.  
  1385.  
  1386.  
  1387.  
  1388.  
  1389.  
  1390. PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))                                                        PPPPEEEERRRRLLLLFFFFAAAAQQQQ8888((((1111))))
  1391.  
  1392.  
  1393.  
  1394.  
  1395.  
  1396.  
  1397.  
  1398.  
  1399.  
  1400.  
  1401.  
  1402.  
  1403.  
  1404.  
  1405.  
  1406.  
  1407.  
  1408.  
  1409.  
  1410.  
  1411.  
  1412.  
  1413.  
  1414.  
  1415.  
  1416.  
  1417.  
  1418.  
  1419.  
  1420.  
  1421.  
  1422.  
  1423.  
  1424.  
  1425.  
  1426.  
  1427.  
  1428.  
  1429.  
  1430.  
  1431.  
  1432.  
  1433.  
  1434.  
  1435.  
  1436.  
  1437.  
  1438.  
  1439.  
  1440.  
  1441.  
  1442.  
  1443.  
  1444.  
  1445.  
  1446.                                                                        PPPPaaaaggggeeee 22222222
  1447.  
  1448.  
  1449.  
  1450.  
  1451.  
  1452.  
  1453.